package org.example.javax.crypto;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

/**
 * 对称加密
 */
public class AESCoder extends Coder{
  static String ALGORITHM = "AES";

  public static Key toKey(byte[] key) throws NoSuchAlgorithmException {
    if (key == null) {
      KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
      kg.init(128);//128, 192 or 256
      SecretKey s = kg.generateKey();
      key = s.getEncoded();
    }
    // 当使用其他对称加密算法时，如AES、Blowfish等算法时，用下述代码替换上述三行代码
    return new SecretKeySpec(key, ALGORITHM);
  }

  public static byte[] decrypt(byte[] data, Key k) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, k);
    return cipher.doFinal(data);
  }

  public static byte[] encrypt(byte[] data, Key k) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, k);
    return cipher.doFinal(data);
  }

}